﻿/*----------------------------------------------------------------
// Copyright (C) 2016 通通优品版权所有。
// 命名空间: TongTongMall.MallWeb.Core.User.Services
// 类名：UserDomainService
// 功能描述：N/A
// 
// 创建标识：Roc.Lee(李鹏鹏) 2017/8/29 14:25:48 TEC-ROCLEE Roc.Lee

// 修改标识：
// 修改描述：
// 
//
//----------------------------------------------------------------*/
using Nito.AsyncEx;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using TongTongMall.Dependecy;
using TongTongMall.Domain.Repositories.Repositories;
using TongTongMall.Domain.Services;
using TongTongMall.Extensions;
using TongTongMall.MallWeb.Core.Authorization.Models;
using TongTongMall.MallWeb.Core.Components;
using TongTongMall.MallWeb.Core.Enums;
using TongTongMall.MallWeb.Core.Events.EventDatas;
using TongTongMall.MallWeb.Core.IRepositories;
using TongTongMall.MallWeb.Core.User.Models;
using TongTongMall.UI;
using TongTongMall.MallWeb.Core.User.Commands;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;

namespace TongTongMall.MallWeb.Core.User.Services
{
    public class UserDomainService : TongTongMallDomainServiceBase, IUserDomainService
    {


        public async Task<AccessTokenDto> Authorization(UserLoginCommand comand)
        {
            var accesstoken = new AccessTokenDto();
            using (var httpClient = new HttpClient())
            {
                httpClient.Timeout = TimeSpan.FromSeconds(10);
                var uri = new Uri(comand.AuthorizationUrl);
                //预热连接
                await httpClient.SendAsync(new HttpRequestMessage
                {
                    Method = new HttpMethod("HEAD"),
                    RequestUri = uri
                });
                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes(comand.Client + ":" + comand.ClientSecret)));
                var parameters = new Dictionary<string, string>
                {
                    {"grant_type", "password"},
                    {"platform", comand.PlatForm},
                    {"username", comand.UserName},
                    {"password", comand.Password}
                };
                if (!comand.SessionKey.IsNullOrEmpty())
                {
                    parameters.Add("sessionkey", comand.SessionKey);
                }
                var resultStr = await httpClient.PostAsync(uri, new FormUrlEncodedContent(parameters)).Result.Content.ReadAsStringAsync();
                try
                {
                    var jObject = JObject.Parse(resultStr).ToObject<JObject>();

                    if (jObject["access_token"] != null)
                    {
                        accesstoken = JsonConvert.DeserializeObject<AccessTokenDto>(resultStr);
                    }
                    else
                    {
                        Logger.Debug("授权服务器验证错误：" + resultStr);
                    }
                }
                catch (Exception ex)
                {
                    // ignored
                    Logger.Warn("授权服务器验证错误：" + resultStr, ex);
                }
            }
            return accesstoken;
        }

        public async Task<AccessTokenDto> SilenceAuthorization(UserLoginCommand comand)
        {
            var accesstoken = new AccessTokenDto();
            using (var httpClient = new HttpClient())
            {
                Uri uri = new Uri(comand.AuthorizationUrl);
                await httpClient.SendAsync(new HttpRequestMessage
                {
                    Method = new HttpMethod("HEAD"),
                    RequestUri = uri
                });
                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes(comand.Client + ":" + comand.ClientSecret)));
                var parameters = new Dictionary<string, string>
                {
                    {"grant_type", "client_credentials"},
                    {"platform", comand.PlatForm}
                };
                var resultStr = await httpClient.PostAsync(uri, new FormUrlEncodedContent(parameters)).Result.Content.ReadAsStringAsync();
                try
                {
                    var jObject = JObject.Parse(resultStr).ToObject<JObject>();
                    if (jObject["access_token"] != null)
                    {
                        accesstoken = JsonConvert.DeserializeObject<AccessTokenDto>(resultStr);
                    }
                    else
                    {
                        Logger.Debug("授权服务器验证错误：" + resultStr);
                    }
                }
                catch
                {
                    // ignored
                }
            }
            return accesstoken;
        }


    }
}
